﻿using System;
using System.IO;

namespace ConsoleApplication1
{
    class Program
    {
        static void Main(string[] args)
        {
            FileStream index = new FileStream("FILEHEADER.TOFHDB", FileMode.Open);
            index.Seek(1198304, SeekOrigin.Begin);
            FileStream content = new FileStream("TLFILE.TLDAT", FileMode.Open);
            int i = 1;
            if (Directory.Exists(".\\TLFILE"))
            {
            }
            else
            {
                Directory.CreateDirectory(".\\TLFILE");
            } 

            while (index.Position<=index.Length)
            {
                byte[] flengthb = new byte[8];
                index.Read(flengthb, 0, 8);
                string flengths = BitConverter.ToString(flengthb);
                flengths = flengths.Replace("-", "");
                int flength = Convert.ToInt32(flengths,16);

                byte[] foffsetb = new byte[8];
                index.Read(foffsetb, 0, 8);
                string foffsets = BitConverter.ToString(foffsetb);
                foffsets = foffsets.Replace("-", "");
                long foffset = Convert.ToInt64(foffsets,16);

                index.Seek(4, SeekOrigin.Current);
                byte[] fextb = new byte[6];
                index.Read(fextb, 0, 6);
                string fext = System.Text.ASCIIEncoding.ASCII.GetString(fextb).Trim(new char[] { '\0' });

                string count = Convert.ToString(i);
                count = count.PadLeft(6,'0');
                i++;

                exportfile(content, flength, foffset, fext, count);

                index.Seek(14, SeekOrigin.Current);
            }
        }

        static void exportfile(FileStream content, int flength, long foffset, string fext, string count)
        {
            byte[] b = new byte[flength];
            content.Seek(foffset, SeekOrigin.Begin);
            content.Read(b, 0, b.Length);
            File.WriteAllBytes(".\\TLFILE\\"+count+"."+fext, b);
        }
    }
}